<?php
if(!defined('IN_SITE')) exit('Access Denied');
$db->table="systemuser";
$filename = "include/data/configure.data.php";
file_exists($filename) && include $filename;
if(!$_SESSION["___isadmin"])
{
   exit("<script language='javascript'>history.back();</script>"); 
}
$info = $db->SelectS("select * from systemuser where id=".$_SESSION["___isadmin"],1);
switch($do)
{
	case "system_set":       
        include(template("system_set"));
    break;
    case "theme_set":
    	$themeDirs = getDirs(FILE_ROOT.'themes');
    	foreach($themeDirs as $themeKey=>$themeDir) {
    		if($themeDir == 'default') { //substr($themeDir,-4) == '_bak'
    			unset($themeDirs[$themeKey]);
    		}
    		else {
	    		$themesInfos = file_exists(FILE_ROOT.'themes/'.$themeDir.'/readme.txt') ? file_get_contents(FILE_ROOT.'themes/'.$themeDir.'/readme.txt') : '';
	    		$themesInfo = explode("\r\n",$themesInfos);
	    		foreach($themesInfo as $themesInfoItem) {
	    			list($themesInfoKey,$themesInfoValue) = explode(':',$themesInfoItem);
	    			$themes[$themeKey]['info'][$themesInfoKey] = iconv('GBK','UTF-8',$themesInfoValue);
	    		}
	    		$themes[$themeKey]['dir'] = $themeDir;
    		}
    	}
        include(template("theme_set"));
    break;
    case "account_set":
    	$info = $db->SelectS("select * from systemuser where id=".$_SESSION["___isadmin"],1);
    	$accounts= $db->SelectS('SELECT * FROM systemuser WHERE id!='.$_SESSION["___isadmin"].' AND username!="admin"');
    	foreach($accounts as $key=>$account) {
    		$accounts[$key]['even'] = intval($key)%2;
    	}
        include(template("account_set"));
    break;
    case "message_set":
    	$showType = post('showType');
	    $conditionReply = post('conditionReply');
	    $conditionDateFrom = post('conditionDateFrom');
	    $conditionDateTo = post('conditionDateTo');
	    $conditionKeyword = post('conditionKeyword');
	    $conditionOrder = post('conditionOrder');
	    if($showType == 'message') {
	    	$where = 'fid=0 AND poster=0';
	    }
	    else if($showType == 'admin_message') {
	    	$where = 'fid=0 AND poster>0';
	    }
	    else {
	    	$where = 'fid=0 AND poster=0';
	    }
	    if($conditionReply == 'replyed') {
	    	$where .= ' AND (SELECT count(*) FROM message WHERE fid = omessage.id) > 0';
	    }
		else if($conditionReply == 'unreplyed') {
	    	$where .= ' AND (SELECT count(*) FROM message WHERE fid = omessage.id) = 0';
	    }
	    if($conditionDateFrom) {
	    	$where .= ' AND createtime >'.strtotime($conditionDateFrom);
	    }
 		if($conditionDateTo) {
	    	$where .= ' AND createtime <'.(strtotime($conditionDateTo)+86400);
	    }
	    if($conditionKeyword) {
		    $where .= ' AND content LIKE "%'.$conditionKeyword.'%" OR nickname LIKE "%'.$conditionKeyword.'%"';
	    }
	    if($conditionOrder == 'time_asc') {
	    	$condition = ' ORDER BY id ASC';
	    }
	    else if($conditionOrder == 'time_desc') {
	    	$condition = ' ORDER BY id DESC';
	    }
    	require_once('include/page.inc.php');
    	$pageNum = $_GET['page'] ? $_GET['page'] : post('pageNum');
    	$params = 'mod=message&act=manage&do=message_set';
    	$page = new Page(array(
			'table'=>"message as omessage",
			'pagesize'=>40,
			'page'=>$_GET['page'],//$pageNum,
			'key'=>'id',
			'where'=>$where,
    		'condition'=>$condition,
			'page_record'=>"条留言",
			'params'=>$params
        ));
        $pagelist = $page->pages();
        if(is_array($pagelist))
        {
            $_pagelist = array();
            foreach($pagelist as $_p) {
				$comments = $db->SelectS("select * from message where fid=".$_p["id"]." ORDER BY id DESC");
				$_p["reply"] = '';
				if(is_array($comments) && count($comments)>0) {
					$_p["reply"] .='<ul class="comment_list">';
					foreach($comments as $commentKey=>$comment) {
						$commentPosterInfo = $db->SelectS("select * from systemuser where id=".$comment['poster'],1);
	                    $_p["reply"] .='<li id="mess_'.$comment['id'].'"><a href="javascript:void(0);" class="name">'.$commentPosterInfo['username'].'</a>'.stripslashes($comment["content"]).'<div>
                                <span class="commentDate">'.date("Y-m-d H:i",$comment['createtime']).'</span><span class="commentBottom"><a href="javascript:void(0);" onClick="delPost('.$comment['id'].');" class="right">删除</a></span></div></li>';
					}
					$_p["reply"] .='</ul>';
				}
				$_p["content"] = strip_tags($_p["content"]);
				$_p["subheader"] = mb_substr($_p["content"],0,30,'UTF-8');
				if(mb_strlen($_p["content"])>30) {
					$_p["subheader"] .= '...';
				}
				$_pagelist[]=$_p;
            }
        }
        $pagestr = $page->SetPageStr();
        //表情
        $faces = include(FILE_ROOT.'/include/face.inc.php');
        include(template("message_set"));
    break;
    case "setsave":
    	$op = post('op');
    	switch($op) {
	    	case 'system':
	    		$configcache = array (
					'pagesize'=>post("pagesize") ? post("pagesize") : $CONFIGURE["pagesize"],
	    			'board_pagesize'=>post("board_pagesize") ? post("board_pagesize") : $CONFIGURE["board_pagesize"],
					'title'=>post("title") ? post("title") : $CONFIGURE["title"],
					'filter'=>post("filter") ? explode("|",post("filter")) : "",
					'weathercityno'=>post("city"),      
	    			'ipInterval'=>post("ipInterval"),   
					'ischeck'=>$CONFIGURE["ischeck"],
					'systemuser'=>$CONFIGURE["systemuser"],
					'tp'=>$CONFIGURE['tp']
				);
    			if ((post("city"))) {
					//如果无city            
					WriteJsWeatherCache(post("city"));//重新生成天气js
					//jsfun("设置成功","?mod=message","top");
				} 
				else {
					$configcache['weathercityno'] = $CONFIGURE['weathercityno'];
				}
	    	break;
	    	case 'account' :
    			/*
				 * 修改帐号或密码
			     */
				if(is_array($info)) {
					$password = post("password");
					$newpassword = post("newpassword");
					$question = post("question");
					$answer = post("answer");
					$errorMsg = 'S';
					if($password && $newpassword) {
						if(md5($password) == $info['password']) {
							$v['UpdateStr'] = array('password'=>md5($newpassword));
							$v['where'] = 'id='.$info["id"].' AND password="'.md5($password).'"';
							if($db->Update($v)){
								$errorMsg = 'S';
							}
							else {
								$errorMsg = 'E';
							}
						}
						else {
							$errorMsg = 'PE';
						}
					}
					if($question != $info["question"] || $answer != $info["answer"]) {
						$v['UpdateStr'] = array('question'=>$question,'answer'=>$answer);
						$v['where'] = 'id='.$info["id"];
						if($db->Update($v)){
							$errorMsg = 'S';
						}
						else {
							$errorMsg = 'E';
						}
					}
				}
				echo $errorMsg;
				exit;
			break;
			case 'theme' :
				$tp= post('tp');
    			$configcache = array (
					'pagesize'=>$CONFIGURE["pagesize"],
    				'board_pagesize'=>$CONFIGURE["board_pagesize"],       
					'title'=>$CONFIGURE["title"],
					'filter'=>$CONFIGURE["filter"],
					'weathercityno'=>$CONFIGURE["weathercityno"],      
	    			'ipInterval'=>$CONFIGURE["ipInterval"],   
					'ischeck'=>$CONFIGURE["ischeck"],
					'systemuser'=>$CONFIGURE["systemuser"],
    				'weathercityno'=>$CONFIGURE['weathercityno'],
					'tp'=>$tp
				);
			break;
	    	case 'message' :
				/**
				 * ip过滤
				 * @var unknown_type
				 */
				$ip  = post("ip")!=""?explode("|",post("ip")):"";
				$_ip = array();
				if($ip!="") {
					foreach($ip as $v) {
						if($v==$_SERVER['REMOTE_ADDR']) {//不能封本机IP
							contionue;
						}
						$_ip[]=$v; 
		            }
				}
			break;
	    	default:
	    		$configcache = array (
					'pagesize'=>$CONFIGURE["pagesize"],
	    			'board_pagesize'=>$CONFIGURE["board_pagesize"],    
					'title'=>$CONFIGURE["title"],
					'filter'=>$CONFIGURE["filter"],
					'weathercityno'=>$CONFIGURE["weathercityno"],      
	    			'ipInterval'=>$CONFIGURE["ipInterval"],   
					'ischeck'=>$CONFIGURE["ischeck"],
					'systemuser'=>$CONFIGURE["systemuser"],
    				'weathercityno'=>$CONFIGURE['weathercityno'],
					'tp'=>$CONFIGURE['tp']
				);
	    	break;
    	}
		WritePhpCache($filename,$configcache,"CONFIGURE");
		exit('success');
    break;
    case 'updateFace':
    	$headface = post('headface');
    	if($_SESSION["___isadmin"]) {
    		$db->query("update systemuser set headpic='".$headface."'"); 
    	}
		exit;
    break;
    case 'addUser':
    	$username = strtolower(post('username'));
    	$password = post('password');
    	$roll = post('roll');
    	if($_SESSION["___isadmin"]) {
    		$info = $db->SelectS('SELECT * FROM systemuser WHERE username="'.$username.'"',1);
			if($info) {
				echo 'UE';//用户名已存在
			}
			else {
				if($db->query("insert into systemuser(username,password,su,createtime) VALUES ('".$username."','".md5($password)."',".$roll.",".time().")")) {
					$lastInsertId = $db->insert_id();
		        	$where = 'id='.$lastInsertId;
		        	$lastData = $db->Select(array('where'=>$where));
					$lastData[0]["createtime"] = date("Y-m-d H:i",$lastData[0]["createtime"]);
		        	echo json_encode($lastData[0]);
		        	exit;
	    		}
	    		else {
	    			echo 'E';//添加用户失败
	    		}
			}
    		
    	}
		exit;
    break;
	case 'editUser' :
		$id = post('id');
    	$password = post('password');
    	if($_SESSION["___isadmin"]) {
			if($db->query("update systemuser set password='".md5($password)."' WHERE id=".$id)) {
				echo 'S';//添加用户成功
    		}
    		else {
    			echo 'E';//添加用户失败
    		}
    	}
		exit;
	break;
	case 'delUser' :
		$id = post('id');
    	if($_SESSION["___isadmin"]) {
			if($db->query("delete from systemuser WHERE id=".$id)) {
				echo 'S';//添加用户成功
    		}
    		else {
    			echo 'E';//添加用户失败
    		}
    	}
		exit;
	break;
	case 'delTheme' :
		$themeFolder = post('themeFolder');
    	if($_SESSION["___isadmin"]) {
			if(delDirs(FILE_ROOT.'themes/'.$themeFolder)) {
			//if(rename(FILE_ROOT.'themes/'.$themeFolder,FILE_ROOT.'themes/'.$themeFolder.'_bak')) {
				echo 'S';//添加用户成功
    		}
    		else {
    			echo 'E';//添加用户失败
    		}
    	}
		exit;
	break;
	case 'page':
    	require_once('include/page.inc.php');
		$start = post('start');
    	$where = "fid=0 and poster=0";
    	$pageNum = post('page');
    	if($start && $pageNum<2) {
    		$where .= ' and id<='.$start;
    	}
        $params = 'mod=message&act=manage&do=message_set';
        $page = new Page(array(
			'table'=>"message",
			'pagesize'=>40,
			'page'=>$pageNum,
			'key'=>'id',
			'where'=>$where,
			'page_record'=>"条留言",
        	'params'=>$params
        ));
        $page->pages();
        $pagestr = $page->SetPageStr();
        echo $pagestr;
        exit;
    break;
    default:
        exit("<script language='javascript'>history.back();</script>");
    break;
}

?>